<template>
    <div class="white-box-1 mb-10 d-flex">
        <div
            v-for="item in 2"
            :key="item"
            class="pd-15 fs-14 cursor hover"
            :style="tabType == item ? tabStyle : ''"
            @click="tabChange(item)"
        >
            <span v-if="item == 1">算法商城</span>
            <span v-else>驱动商城</span>
        </div>
    </div>
    <div class="white-box fs-14 d-flex-1 ps-re" style="height: 100%">
        <div class="d-flex">
            <div>
                {{ `${tabState.get(tabType)}名称` }}
            </div>
            <div class="ml-10">
                <el-input
                    v-model="form.algorithm_name"
                    :placeholder="`请输入${tabState.get(tabType)}名称`"
                />
            </div>
            <div class="ml-10">
                <el-button type="primary" @click="getData(tabType)"
                    >搜索</el-button
                >
            </div>
        </div>
        <div class="d-flex mt-20">
            <div class="mr-10">应用分类</div>
            <div
                v-for="item in activeType"
                :key="item.type"
                class="pd-5-10 cursor bg-gray mr-10"
                :style="activeIndex == item.type ? activeStyle : ''"
                @click="activeTab(item)"
            >
                {{ item.name }}
            </div>
        </div>
        <div class="fl-bw d-flex-middle mt-10">
            <div style="color: red">
                <span v-if="tabType == 1"
                    >说明：付费算法购买后仅供一路摄像头使用。如需多路摄像头同时使用相同算法，请按需购买多次/多个。</span
                >
            </div>
            <div class="svgStyle">
                <div
                    v-for="item in 2"
                    @click="ChangeShowtab(item)"
                    :style="
                        showtab == item
                            ? 'border-color:var(--el-color-primary)'
                            : ''
                    "
                    :key="item"
                >
                    <span
                        class="icon"
                        :style="
                            showtab == item
                                ? 'color:var(--el-color-primary)'
                                : ''
                        "
                        >{{ item == 1 ? '&#xe60b;' : '&#xe67c;' }}</span
                    >
                </div>
            </div>
        </div>

        <el-table
            :data="tableData"
            style="width: 100%"
            class="mt-30"
            v-if="showtab == 1"
        >
            <el-table-column prop="algorithm_name" label="软件名称" />
            <el-table-column
                prop="introduction"
                label="说明"
                width="500"
                show-overflow-tooltip
            />
            <el-table-column prop="cost" label="价格" />
            <el-table-column :label="tabType == 1 ? '版本' : '型号'">
                <template #default="scope">
                    <div class="dflex" v-if="scope.row.update_available == '1'">
                        <h5>
                            {{
                                scope.row.user_version == ''
                                    ? scope.row.version
                                    : scope.row.user_version
                            }}
                        </h5>
                    </div>
                    <div class="dflex" v-else>
                        {{scope.row.user_version}}
                        <h5 style="color: red" class="ml-5">
                            >>> {{ scope.row.version }}
                        </h5>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="scope">
                    <el-badge is-dot class="item"  v-if="scope.row.update_available == '2'">
                        <el-button
                            link
                            type="primary"
                            @click="updateData(scope.row)"
                           
                        >
                            升级
                        </el-button>
                    </el-badge>
                    <el-button
                        v-else
                        type="primary"
                        link
                        @click="loadingData(scope.row)"
                    >
                        {{
                            scope.row.status ? '正在加载...' : '加载'
                        }}</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <div v-if="showtab == 2">
            <el-empty description="暂无数据" v-if="tableData.length == 0" />
            <div v-else class="mt-10">
                <el-row :gutter="20">
                    <el-col :span="6" v-for="item in tableData" :key="item">
                        <div class="iot-card">
                            <el-tag
                                class="type"
                                effect="dark"
                                type="danger"
                                size="small"
                                v-if="item.update_available == '2'"
                            >
                                可升级
                            </el-tag>
                            <div class="iot-card-content">
                                <div class="img">
                                    <img
                                        src="../../assets/images/sms.png"
                                        alt=""
                                    />
                                </div>
                                <div class="details">
                                    <div class="d-flex mb-5 d-flex-between">
                                        <div class="title">
                                            {{ item.algorithm_name }}
                                        </div>
                                        <div style="color: red">
                                            {{ item.cost }}
                                        </div>
                                    </div>
                                    <div
                                        class="dflex"
                                        v-if="item.update_available == '1'"
                                    >
                                        <h5>
                                            {{
                                                tabType == 1 ? '版本' : '型号'
                                            }}：{{
                                                item.user_version == ''
                                                    ? item.version
                                                    : item.user_version
                                            }}
                                        </h5>
                                    </div>
                                    <div class="dflex" v-else>
                                        <h5>
                                            {{
                                                tabType == 1 ? '版本' : '型号'
                                            }}：{{ item.user_version }}
                                        </h5>
                                        <h5 style="color: red" class="ml-5">
                                            >>> {{ item.version }}
                                        </h5>
                                    </div>
                                    <el-row>
                                        <el-col :span="24">
                                            <h5>说明</h5>
                                            <p class="line">
                                                {{ item.introduction }}
                                            </p>
                                        </el-col>
                                    </el-row>
                                </div>
                                <div class="card-content-bg1"></div>
                                <div class="card-content-bg2"></div>
                            </div>
                            <el-progress
                                v-if="item.state && item.num !== 100"
                                class="mt-20"
                                :text-inside="true"
                                :stroke-width="15"
                                :percentage="item.num"
                                striped-flow
                                striped
                                :duration="10"
                            />
                            <div
                                class="iot-card-oper"
                                v-else-if="item.update_available == '2'"
                            >
                                <div class="card-button">
                                    <el-button link @click="updateData(item)">
                                        升级
                                    </el-button>
                                </div>
                            </div>
                            <div class="iot-card-oper" v-else>
                                <div class="card-button">
                                    <el-button link @click="loadingData(item)">
                                        加载
                                    </el-button>
                                </div>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>
        <div class="ps-ab ps-b-10 ps-r-20">
            <el-pagination
                small
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                layout="prev, pager, next, jumper"
                v-model:total="total"
                @current-change="handleCurrentChange"
                v-if="total > 0"
            />
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, onUnmounted, watch, nextTick, onMounted } from 'vue'
import {
    getAlgorithmShopList,
    setAuthorization,
    getdownloadDrive,
    updateAlgorithm,
} from '@/assets/api/device'
import { useUserStore } from '@/stores/index'
const userStore = useUserStore()
import { showMsg } from '@/assets/js/utils'
import config from '@/assets/js/config'

// 顶部切换样式
const tabStyle = ref({
    background: 'rgba(29, 57, 196, 0.1)',
    color: 'var(--el-color-primary)',
})
// 顶部切换状态
const tabType = ref(1)
// 应用分类
const activeIndex = ref(0)
// 应用状态
const activeStyle = ref({
    background: 'var(--el-color-primary)',
    color: '#fff',
})
// 应用分类
const activeType = ref([
    {
        name: '全部',
        type: '0',
    },
    {
        name: '免费应用',
        type: '2',
        cost: '免费',
    },
])
const tableData = ref([])
const showtab = ref('2')
const currentPage = ref(1)
const pageSize = 8
const total = ref(0)
const form = reactive({
    page: currentPage,
    limit: pageSize,
})
const tabState = new Map([
    [1, '算法'],
    [2, '驱动'],
])
// 表格/模块切换
const ChangeShowtab = (tab) => {
    showtab.value = tab
}
// 驱动/算法切换
const tabChange = (tab) => {
    tabType.value = tab
    getData(tab)
}
function activeTab(item) {
    activeIndex.value = item.type
    form.cost = item.cost
}
function getData(tab = 1) {
    // type 1 算法 2 驱动商城
    form.type = tab
    getAlgorithmShopList(form).then((res) => {
        nextTick(() => {
            tableData.value = res.data.Items
            total.value = res.data.totalSize
            tableData.value.forEach((item) => {
                item.status = false
            })
        })
    })
}
const loading = ref()
function loadingData(item) {
    let data = tableData.value.find((item) => item.state)
    if (data && data.num < 100) {
        showMsg('请等待当前任务下载完成', 'error')
        return
    }
    item.status = true
    if (tabType.value == 1) {
        setAuthorization({
            algorithm_name: item.algorithm_name,
            license_information: userStore.systemInfo.gatewayPermit,
            authorization_status: 'authorize',
        })
            .then(() => {
                item.num = 100
                item.status = false
                showMsg('操作成功')
                getData()
            })
            .catch(() => {
                item.status = false
                showMsg('操作失败', 'error')
            })
        return
    }
    getdownloadDrive({ url: item.model_url })
        .then(() => {
            item.status = false
            showMsg('操作成功')
        })
        .catch(() => {
            item.status = true
            showMsg('操作失败', 'error')
        })
}
getData()
function handleCurrentChange(e) {
    currentPage.value = e
    getData()
}
function getSchedule(name, num) {
    tableData.value.forEach((item) => {
        if (name == item.algorithm_name) {
            nextTick(() => {
                item.num = num
                item.state = true
            })
        }
    })
}
const ws = new WebSocket(config.socketUrl)
function openSocket() {
    //  //连接发生错误的回调方法
    ws.onerror = function () {
        console.log('ws连接发生错误')
    }
    //连接成功建立的回调方法
    ws.onopen = function () {
        console.log('ws连接成功')
    }
    //接收到消息的回调方法
    ws.onmessage = function (msg) {
        let data = JSON.parse(msg.data)
        getSchedule(data.algorithm_name, Number(data.data))
    }
    //连接关闭的回调方法
    ws.onclose = function () {
        console.log('ws连接关闭')
    }
}
function updateData(val) {
    updateAlgorithm({
        license_information: userStore.systemInfo.gatewayPermit,
        algorithm_name: val.algorithm_name,
        version: val.version,
    }).then((res) => {
        if (res.code == 0) {
            showMsg('操作成功')
            getData()
        }
    })
}
onMounted(() => {
    openSocket()
})
onUnmounted(() => {
    //连接关闭的回调方法
    ws.close()
})
</script>
<style lang="scss" scoped>
:deep(.el-tabs__nav-wrap) {
    background: #fff !important;
    border-radius: 5px;
    .el-tabs__item.is-active {
        background: rgba(29, 57, 196, 0.1);
    }
    .el-tabs__item {
        border-bottom: none;
    }
}
:deep(.el-tabs__content) {
    flex: 1;
    background: #fff;
}
.el-tabs {
    flex: 1 !important;
    display: flex !important;
    flex-direction: column !important;
}
.svgStyle {
    display: flex;
    align-items: center;
    div {
        border: 1px solid #c5c6c8;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    span {
        cursor: pointer;
        color: #c5c6c8;
        font-size: 18px;
    }
}
.iot-card-content .img > img {
    width: 80px;
    height: 80px;
}
.card-content-bg2 {
    position: absolute;
    right: -5%;
    height: 100%;
    width: calc(44.65% + 34px);
    top: 0;
    background: linear-gradient(
        188.4deg,
        rgba(102, 102, 102, 0.03) 30%,
        rgba(102, 102, 102, 0) 80%
    );
    transform: skewX(-15deg);
}
.card-content-bg1 {
    position: absolute;
    right: -5%;
    height: 100%;
    width: 44.65%;
    top: 0;
    background: linear-gradient(
        188.4deg,
        rgba(102, 102, 102, 0.03) 30%,
        rgba(102, 102, 102, 0) 80%
    );
    transform: skew(-15deg);
}
.iot-card-content {
    padding: 0 0.1rem !important;
    height: 1rem;
}
.iot-card {
    position: relative;
    .title {
        cursor: pointer;
        font-size: 18px;
        font-weight: 700;
        color: #315efb;
        width: calc(100% - 0.220833rem);
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin: 0;
    }
    .card-button {
        height: 40px !important;
        margin: 0;
        button {
            margin-top: 3px;
        }
    }
    .type {
        position: absolute;
        top: 10px;
        left: 10px;
        width: 50px;
    }
}
.hover {
    border: 1px solid #e6e6e6;
    &:hover {
        color: --el-color-primary;
    }
}
:deep(.el-badge__content.is-fixed.is-dot) {
    right: 0px !important;
    top: 3px !important;
}
</style>
